<script setup lang="ts">
import { getUserAddress, getUserAddressList } from "@/api/address/address";
import { getCartItmeList } from "@/api/cart/cartItem";
import { addOrder } from "@/api/order/order";
import router from "@/router";
import { ElMessage, ElMessageBox, type Action, type FormInstance, type UploadFile } from "element-plus";
import { reactive, ref, toRefs } from "vue";
import type {Product,CartItem} from "@/types/index"
const AddressData = ref();
const userAddress=ref()
const formEl=ref()
interface order{
  addressId:number | null,
  paymentMethod: number,
  shippingMethods: number,
  merchantId:number,
  totalAmount:number,
  status:number,
  cartItemList:CartItem[],
  isDelete:number
}
const addressIdValidator = (rule: any, value: any, callback: any) => {
  if (!value ) {
    callback(new Error("请选择收货地址"));
  } else {
    callback();
  }
};
const loading =ref(false)
const data = reactive({
  form:<order>{
  paymentMethod: 1,
  shippingMethods: 1,
  status:1,
  isDelete:0
},
  rules:{
     addressId: [
      {
        required: true,
        validator: addressIdValidator,
        trigger: "blur",
      },
    ],}
})
const {form,rules} =toRefs(data)
//初始化
async function load() {
  loading.value=true
  await getUserAddressList().then(async (response) => {
    AddressData.value = response.data.rows;
    if (AddressData.value.length > 0) {
      const isDef=AddressData.value.filter(
        (item: any) => item.isDefault === 1
      )
      if(isDef.length >0){
        form.value.addressId = isDef[0].userAddressId
        await getUserAddress(form.value.addressId).then(response=>{userAddress.value=response.data.data})
      }
    } else {
      ElMessageBox.alert("您还没创建收货地址哦~", "提示", {
        confirmButtonText: "去创建",
        callback: (action: Action) => {
          router.push("/address")
    },
      })

    }
  });
  await getCartItmeList().then((response) => {
    form.value.cartItemList = response.data.data.cartItemList.filter((item: any) => item.isChosen === 1);
    form.value.totalAmount=response.data.data.totalAmount
  });
  loading.value=false
}

//地址选中发生变化时
const radioAddress=()=>{
  getUserAddress(form.value.addressId).then(response=>{userAddress.value=response.data.data})
}

//提交按钮
const submitOder = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      await addOrder(form.value)
      ElMessage({
    message: '付款成功',
    type: 'success',
  })
       router.push("/orders")

    }
  });
};

load();
</script>
<template>
  <el-form
    v-if="form.cartItemList !== undefined && form.cartItemList.length > 0"
    :model="form"
    ref="formEl"
    :rules="rules"
    v-loading="loading"
  >
    <h1>填写并核对订单信息</h1>
    <el-card shadow="never">
      <h4>收货人信息</h4>
      <el-form-item prop="addressId">
        <el-radio-group v-model="form.addressId" @change="radioAddress">
          <el-radio
            v-for="item in AddressData"
            :value="item.userAddressId"
            size="large"
            border
            >{{ item.receiverName }}{{ item.receiverPhone }}{{ item.province
            }}{{ item.city }}{{ item.district }}{{ item.street
            }}<span style="margin-left: 4px; color: cadetblue">{{
              item.isDefault == 1 ? "默认地址" : ""
            }}</span></el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-divider />
      <h4>支付方式</h4>
      <div>
        <el-radio-group v-model="form.paymentMethod">
          <el-radio
            v-for="item in form.paymentMethod"
            :value="item"
            size="large"
            border
            >{{ item == 1 ? "在线支付" : "" }}</el-radio
          >
        </el-radio-group>
      </div>
      <el-divider />
      <h4>送货清单</h4>
      <el-card
        shadow="never"
        v-for="item in form.cartItemList"
        style="margin-top: 10px; background-color: aliceblue"
      >
        <el-row>
          <el-col :span="4">
            <div style="display: inline-block">
              <span>配送方式</span>
              <div>
                <el-radio-group v-model="form.shippingMethods">
                  <el-radio v-for="item in 1" :value="1" size="large" border>{{
                    item == 1 ? "快递运输" : ""
                  }}</el-radio>
                </el-radio-group>
              </div>
            </div>
          </el-col>

          <el-col :span="3">
            <div style="display: inline-block">
              <el-image
                style="width: 100px; height: 100px"
                :src="item.product.img"
                fit="fill"
              />
            </div>
          </el-col>
          <el-col :span="6">
            <div style="display: inline-block">
              <!-- <div>商家:{{ item.product.merchantName }}</div> -->
              <div>商品名称:{{ item.product.name }}</div>
              <div>详情:{{ item.product.description }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <el-text type="danger">
              ￥{{ Number(item.product.price).toFixed(2) }}到手价</el-text
            >
          </el-col>
          <el-col :span="4"> x{{ item.quantity }} </el-col>
          <el-col :span="2"> {{ item.product.stock > 0 ? "有货" : "无货购买" }} </el-col>
          <el-divider />
        </el-row>
      </el-card>
    </el-card>
    <div
      style="
        text-align: end;
        width: 100%;
        background-color: #f4f4f4;
        padding: 10px 0 10px 0;
        line-height: 20px;
      "
    >
      <div style="margin-right: 20px">
        <span>应付总额:￥{{ Number(form.totalAmount).toFixed(2) }}</span>
      </div>
      <div style="margin-right: 20px" v-if="userAddress != undefined">
        寄送至： {{ userAddress.province }} {{ userAddress.city }}
        {{ userAddress.district }} {{ userAddress.street }} 收货人：{{
          userAddress.receiverName
        }}
        {{ userAddress.receiverPhone }}
      </div>
    </div>
    <div style="text-align: end">
      <el-button
        @click="submitOder(formEl)"
        style="margin: 20px"
        size="large"
        type="danger"
        >立即付款</el-button
      >
    </div>
  </el-form>
  <div v-else style="text-align: center">
    <el-link @click="router.push('/home')" target="_blank"
      >没有相关结算信息哦~点击我回到首页</el-link
    >
  </div>
</template>
<style lang="less">
.el-radio-group {
  flex-direction: column;
  align-items: flex-start;
}
.el-radio.is-bordered.el-radio--large {
  margin: 5px;
}
.el-steps--simple {
  background: #ffffff;
}
</style>
